
import os
import time
import sqlite3
from datetime import datetime
from threading import Thread, Lock
from queue import Queue


class ActionQueue:
    class Message:
        def __init__(self, mid, msg):
            self.mid = mid
            self.msg = msg

    def __init__(self):
        super().__init__()
        self.request_queue = Queue()
        self.next_mid = 0
        self.lock = Lock()

        self.response_queue = Queue()

    def request(self, msg):
        self.lock.acquire()
        mid = self.next_mid
        self.next_mid += 1
        self.lock.release()

        self.request_queue.put(ActionQueue.Message(mid, msg))
        print("request:", (mid, msg))
        return mid

    def read_request(self):
        return self.request_queue.get()

    def response(self, mid, response):
        print("response:", mid)
        self.response_queue.put(ActionQueue.Message(mid, response))

    def wait_response(self, mid):
        res = self.response_queue.get()
        count = 0
        while res.mid != mid:
            self.response_queue.put(res)
            if count > 10000:
                res = None
                break
            res = self.response_queue.get()

        return res

    def no_more_request(self):
        return self.request_queue.empty()


class VisitRecordTable:
    def __init__(self, workspace):
        self.workspace = workspace
        self.db = os.path.join(self.workspace.path, 'visit_record.db')
        self.queue = ActionQueue()
        t = Thread(target=VisitRecordTable.run, args=(self,))
        t.start()

    def insert(self, ip, url):
        visit_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        mid = self.queue.request(f"insert into visit_record values('{ip}', '{visit_time}', '{url}')")
        self.queue.wait_response(mid)
        return

    def statistic(self):
        """
        总访问量
        访问曲线（时间、访问量）
        用户访问表(用户、访问次数)
        页面访问表(页面，访问次数)
        """
        pass

    @staticmethod
    def run(vrt):
        conn = sqlite3.connect(vrt.db)
        curs = conn.cursor()
        curs.execute("create table if not exists visit_record (ip text, time text, url text);")
        while True:
            while not vrt.queue.no_more_request():
                req = vrt.queue.read_request()
                curs.execute(req.msg)
                vrt.queue.response(req.mid, "ok")

            time.sleep(1)

